<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { io, Socket } from "socket.io-client"


// webrtc关键的API
// 1.使用navigator.mediaDevices.getUserMedia 获取用户的音视频
/* navigator.mediaDevices.getUserMedia({
  video: true,
  audio: true,
}) */

//  通过信令服务器（当前使用websocket） 进行交互数据

/**
 * 2.通过 RTCPeerConnection 进行
 * 媒体协商方法：
 * 1.createOffer 呼叫端创建offer信息（SDP信息）发给接收端 
 * 2.createAnswer 接收端收到offer信息 创建answer信息（SDP信息）发送给呼叫端
 * 3.setLocalDesccription  存储己方SDP信息(offer信息)到本地
 * 4.setRemoteDesccription  存储接收到的SDP信息（offer/answer信息）
 * 
 * 重要事件：
 * onicecandidate
 * onaddstream
 * 
 * 经过上述三个步骤，则完成了 P2P 通信过程中的媒体协商部分，
 * 实际上在呼叫端以及接收端调用setLocalDesccription 同时也开始了收集各端自己的网络信息(candidate)，
 * 然后各端通过监听事件 onicecandidate 收集到各自的 candidate 并通过信令服务器传送给对端，
 * 进而打通 P2P 通信的网络通道，
 * 并通过监听 onaddstream 事件拿到对方的视频流进而完成了整个视频通话过程。
 */

const ROOM_ID = "001"  //定义个双方音视频通讯的聊天房间号
const socket = ref<Socket>() // 存储Socket实例
const called = ref<boolean>(false) // 是否是接收方
const caller = ref<boolean>(false) // 是否是发起方
const calling = ref<boolean>(false) // 呼叫中
const communicating = ref<boolean>(false) // 视频通话中
const localVideo = ref<HTMLVideoElement>() // video标签实例，播放本人的视频
const remoteVideo = ref<HTMLVideoElement>() // video标签实例，播放对方的视频

const localStream = ref() // 用于存储本地的音视频流

const peer = ref<RTCPeerConnection | null>(null) // 存储对应呼叫端或接收端的RTCPeerConnection实例对象


const getLocalStream = async () => {
  const stream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true,
  })
  // 赋值获取到流并播放
  localVideo.value!.srcObject = stream
  localVideo.value!.play()

  localStream.value = stream

  return stream
}
// 发起方发起视频请求
const callRemote = async () => {
  console.log('发起视频');
  caller.value = true  // 表示是发起端
  calling.value = true // 通话中
  await getLocalStream()
  // 向信令服务器发送发起请求事件
  socket.value?.emit("callRemote", ROOM_ID)
}

// 接收方同意视频请求
const acceptCall = () => {
  console.log('同意视频邀请');
  // 通过信令服务器发送接受视频的事件
  socket.value?.emit("acceptCall", ROOM_ID)

}

// 挂断视频
const hangUp = () => {
  console.log('挂断视频');
  socket.value?.emit("hangUp", ROOM_ID)
}

const reset = () => {
  called.value = false
  caller.value = false
  calling.value = false
  communicating.value = false
  peer.value = null
  localVideo.value!.srcObject = null
  remoteVideo.value!.srcObject = null
  localStream.value = undefined
}

onMounted(() => {
  // 连接websocket
  const sock = io("localhost:3004") // 对应服务的端口

  // 监听连接是否成功
  sock.on("connectionSuccess", () => {
    console.log("连接成功")
    // 连接成功后 去加入房间 （呼叫端和接收端共有的逻辑）
    sock.emit("joinRomm", ROOM_ID)

    // 监听发送端发来的视频请求 （接收端的逻辑）
    sock.on("callRemote", () => {
      // 只有接收方才需要做处理
      if (!caller.value) {
        called.value = true // 表示为是接收方
        calling.value = true // 通话中
      }
    })

    // 监听接收端同意的视频请求  （呼叫端的逻辑）
    sock.on("acceptCall", async () => {
      if (caller.value) {
        // console.log("呼叫端得到的信息===>： 接收方同意了视频请求")
        peer.value = new RTCPeerConnection()
        // 添加本地音视频流
        for (const track of localStream.value.getTracks()) {
          peer.value.addTrack(track, localStream.value)
        }

        // 当呼叫方 设置了己方的offer信息 + 接收方的answer 会触发onicecandidate事件
        peer.value.onicecandidate = (event) => {
          if (event.candidate) {
            // console.log("event.candidate：", event.candidate)
            // 将呼叫端的candidate信息发送给接收端
            sock.emit("sendCandidate", {
              roomId: ROOM_ID,
              candidate: event.candidate,
              from: "caller"
            })
          }
        }

        // 监听onaddstream来获取对方的音视频流
        peer.value.ontrack = (event) => {
          // console.log("呼叫端的ontrack事件：", event.streams)
          calling.value = false;
          communicating.value = true;
          remoteVideo.value!.srcObject = event.streams[0]
          remoteVideo.value!.play()
        }

        // 生成offer
        const offer = await peer.value.createOffer({
          offerToReceiveAudio: true,
          offerToReceiveVideo: true
        })
        /**
         * offer的数据  也就是SDP信息
         * {
              "sdp": "v=0\r\no=- 4302709431376765705 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:QopD\r\na=ice-pwd:tJ27peFkxehAAKXVfkCqUoC6\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA:41:80:1A:F7:30:8C:0B:97:55:BC:2C:7C:71:E6:25:09:B6:7E:3B:82:64:8B:CB:F2:FB:2F:FD:48:E3:2F:7C\r\na=setup:actpass\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=sendrecv\r\na=msid:- 0918f2d0-b55c-4b79-8a5e-730507ed94a4\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:834896216 cname:0j7SRrprUwJZpDcB\r\na=ssrc:834896216 msid:- 0918f2d0-b55c-4b79-8a5e-730507ed94a4\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97 103 104 107 108 109 114 115 116 117 118 39 40 45 46 98 99 100 101 123 124 125\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:QopD\r\na=ice-pwd:tJ27peFkxehAAKXVfkCqUoC6\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA:41:80:1A:F7:30:8C:0B:97:55:BC:2C:7C:71:E6:25:09:B6:7E:3B:82:64:8B:CB:F2:FB:2F:FD:48:E3:2F:7C\r\na=setup:actpass\r\na=mid:1\r\na=extmap:14 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:13 urn:3gpp:video-orientation\r\na=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\na=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type\r\na=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing\r\na=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space\r\na=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\na=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\na=sendrecv\r\na=msid:- 3b05e60f-e29f-4a2c-88e3-3333ec3e17a8\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:96 VP8/90000\r\na=rtcp-fb:96 goog-remb\r\na=rtcp-fb:96 transport-cc\r\na=rtcp-fb:96 ccm fir\r\na=rtcp-fb:96 nack\r\na=rtcp-fb:96 nack pli\r\na=rtpmap:97 rtx/90000\r\na=fmtp:97 apt=96\r\na=rtpmap:103 H264/90000\r\na=rtcp-fb:103 goog-remb\r\na=rtcp-fb:103 transport-cc\r\na=rtcp-fb:103 ccm fir\r\na=rtcp-fb:103 nack\r\na=rtcp-fb:103 nack pli\r\na=fmtp:103 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f\r\na=rtpmap:104 rtx/90000\r\na=fmtp:104 apt=103\r\na=rtpmap:107 H264/90000\r\na=rtcp-fb:107 goog-remb\r\na=rtcp-fb:107 transport-cc\r\na=rtcp-fb:107 ccm fir\r\na=rtcp-fb:107 nack\r\na=rtcp-fb:107 nack pli\r\na=fmtp:107 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f\r\na=rtpmap:108 rtx/90000\r\na=fmtp:108 apt=107\r\na=rtpmap:109 H264/90000\r\na=rtcp-fb:109 goog-remb\r\na=rtcp-fb:109 transport-cc\r\na=rtcp-fb:109 ccm fir\r\na=rtcp-fb:109 nack\r\na=rtcp-fb:109 nack pli\r\na=fmtp:109 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f\r\na=rtpmap:114 rtx/90000\r\na=fmtp:114 apt=109\r\na=rtpmap:115 H264/90000\r\na=rtcp-fb:115 goog-remb\r\na=rtcp-fb:115 transport-cc\r\na=rtcp-fb:115 ccm fir\r\na=rtcp-fb:115 nack\r\na=rtcp-fb:115 nack pli\r\na=fmtp:115 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f\r\na=rtpmap:116 rtx/90000\r\na=fmtp:116 apt=115\r\na=rtpmap:117 H264/90000\r\na=rtcp-fb:117 goog-remb\r\na=rtcp-fb:117 transport-cc\r\na=rtcp-fb:117 ccm fir\r\na=rtcp-fb:117 nack\r\na=rtcp-fb:117 nack pli\r\na=fmtp:117 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f\r\na=rtpmap:118 rtx/90000\r\na=fmtp:118 apt=117\r\na=rtpmap:39 H264/90000\r\na=rtcp-fb:39 goog-remb\r\na=rtcp-fb:39 transport-cc\r\na=rtcp-fb:39 ccm fir\r\na=rtcp-fb:39 nack\r\na=rtcp-fb:39 nack pli\r\na=fmtp:39 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f\r\na=rtpmap:40 rtx/90000\r\na=fmtp:40 apt=39\r\na=rtpmap:45 AV1/90000\r\na=rtcp-fb:45 goog-remb\r\na=rtcp-fb:45 transport-cc\r\na=rtcp-fb:45 ccm fir\r\na=rtcp-fb:45 nack\r\na=rtcp-fb:45 nack pli\r\na=fmtp:45 level-idx=5;profile=0;tier=0\r\na=rtpmap:46 rtx/90000\r\na=fmtp:46 apt=45\r\na=rtpmap:98 VP9/90000\r\na=rtcp-fb:98 goog-remb\r\na=rtcp-fb:98 transport-cc\r\na=rtcp-fb:98 ccm fir\r\na=rtcp-fb:98 nack\r\na=rtcp-fb:98 nack pli\r\na=fmtp:98 profile-id=0\r\na=rtpmap:99 rtx/90000\r\na=fmtp:99 apt=98\r\na=rtpmap:100 VP9/90000\r\na=rtcp-fb:100 goog-remb\r\na=rtcp-fb:100 transport-cc\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 nack pli\r\na=fmtp:100 profile-id=2\r\na=rtpmap:101 rtx/90000\r\na=fmtp:101 apt=100\r\na=rtpmap:123 red/90000\r\na=rtpmap:124 rtx/90000\r\na=fmtp:124 apt=123\r\na=rtpmap:125 ulpfec/90000\r\na=ssrc-group:FID 2237729273 326298512\r\na=ssrc:2237729273 cname:0j7SRrprUwJZpDcB\r\na=ssrc:2237729273 msid:- 3b05e60f-e29f-4a2c-88e3-3333ec3e17a8\r\na=ssrc:326298512 cname:0j7SRrprUwJZpDcB\r\na=ssrc:326298512 msid:- 3b05e60f-e29f-4a2c-88e3-3333ec3e17a8\r\n",
              "type": "offer"
            }
         */
        // 设置本地描述的offer
        await peer.value.setLocalDescription(offer)
        // 通过信令服务器将offer发送给接收端
        sock.emit("sendOffer", { offer, roomId: ROOM_ID })
      }

    })

    // 接收端接收呼叫端发来的SDP信息 / offer信息  （接收端的逻辑）
    sock.on("sendOffer", async (offer) => {
      // 只在接收端做处理
      if (called.value) {
        // console.log("接收端得到的信息===>：成功接到呼叫端发来的offer信息")
        const stream = await getLocalStream()
        // 创建自己的RTCPeerConnection
        peer.value = new RTCPeerConnection()
        // 添加本地音视频流
        for (const track of stream.getTracks()) {
          peer.value.addTrack(track, stream)
        }

        peer.value.onicecandidate = (event) => {
          if (event.candidate) {
            // console.log('接收端触发onicecandidate事件：', event.candidate);
            // 通过信令服务器发送candidate信息给呼叫端
            sock.emit("sendCandidate", {
              roomId: ROOM_ID,
              candidate: event.candidate,
              from: "called"
            })
          }
        }

        // 监听onaddstream来获取对方的音视频流
        peer.value.ontrack = (event) => {
          // console.log("接收端的ontrack事件：", event.streams)
          calling.value = false;
          communicating.value = true;
          remoteVideo.value!.srcObject = event.streams[0]
          remoteVideo.value!.play()
        }
        // 设置远端描述信息
        await peer.value.setRemoteDescription(offer)
        const answer = await peer.value.createAnswer()
        // 设置生成answer信息
        await peer.value.setLocalDescription(answer)
        /**
         * answer: {
              "sdp": "v=0\r\no=- 7447250263304018872 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:vXZW\r\na=ice-pwd:Glhf3vmqtdaS8OVVYuT1Tfje\r\na=ice-options:trickle\r\na=fingerprint:sha-256 09:72:7D:76:7F:F7:DA:F3:25:DE:6C:6C:C7:89:1E:80:7A:46:CA:44:E1:0E:ED:3B:7E:0F:06:B8:73:9C:DA:48\r\na=setup:active\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=sendrecv\r\na=msid:- a79cf06e-2923-4534-8a5c-bce6b0fb1544\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:1130462945 cname:XTjS0iKTUJWj00ys\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97 103 104 107 108 109 114 115 116 117 118 39 40 45 46 98 99 100 101 123 124 125\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:vXZW\r\na=ice-pwd:Glhf3vmqtdaS8OVVYuT1Tfje\r\na=ice-options:trickle\r\na=fingerprint:sha-256 09:72:7D:76:7F:F7:DA:F3:25:DE:6C:6C:C7:89:1E:80:7A:46:CA:44:E1:0E:ED:3B:7E:0F:06:B8:73:9C:DA:48\r\na=setup:active\r\na=mid:1\r\na=extmap:14 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:13 urn:3gpp:video-orientation\r\na=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\na=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type\r\na=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing\r\na=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space\r\na=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\na=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\na=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\na=sendrecv\r\na=msid:- 0c22aa32-f080-437c-b4c0-37a1b0db3863\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:96 VP8/90000\r\na=rtcp-fb:96 goog-remb\r\na=rtcp-fb:96 transport-cc\r\na=rtcp-fb:96 ccm fir\r\na=rtcp-fb:96 nack\r\na=rtcp-fb:96 nack pli\r\na=rtpmap:97 rtx/90000\r\na=fmtp:97 apt=96\r\na=rtpmap:103 H264/90000\r\na=rtcp-fb:103 goog-remb\r\na=rtcp-fb:103 transport-cc\r\na=rtcp-fb:103 ccm fir\r\na=rtcp-fb:103 nack\r\na=rtcp-fb:103 nack pli\r\na=fmtp:103 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f\r\na=rtpmap:104 rtx/90000\r\na=fmtp:104 apt=103\r\na=rtpmap:107 H264/90000\r\na=rtcp-fb:107 goog-remb\r\na=rtcp-fb:107 transport-cc\r\na=rtcp-fb:107 ccm fir\r\na=rtcp-fb:107 nack\r\na=rtcp-fb:107 nack pli\r\na=fmtp:107 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f\r\na=rtpmap:108 rtx/90000\r\na=fmtp:108 apt=107\r\na=rtpmap:109 H264/90000\r\na=rtcp-fb:109 goog-remb\r\na=rtcp-fb:109 transport-cc\r\na=rtcp-fb:109 ccm fir\r\na=rtcp-fb:109 nack\r\na=rtcp-fb:109 nack pli\r\na=fmtp:109 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f\r\na=rtpmap:114 rtx/90000\r\na=fmtp:114 apt=109\r\na=rtpmap:115 H264/90000\r\na=rtcp-fb:115 goog-remb\r\na=rtcp-fb:115 transport-cc\r\na=rtcp-fb:115 ccm fir\r\na=rtcp-fb:115 nack\r\na=rtcp-fb:115 nack pli\r\na=fmtp:115 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f\r\na=rtpmap:116 rtx/90000\r\na=fmtp:116 apt=115\r\na=rtpmap:117 H264/90000\r\na=rtcp-fb:117 goog-remb\r\na=rtcp-fb:117 transport-cc\r\na=rtcp-fb:117 ccm fir\r\na=rtcp-fb:117 nack\r\na=rtcp-fb:117 nack pli\r\na=fmtp:117 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f\r\na=rtpmap:118 rtx/90000\r\na=fmtp:118 apt=117\r\na=rtpmap:39 H264/90000\r\na=rtcp-fb:39 goog-remb\r\na=rtcp-fb:39 transport-cc\r\na=rtcp-fb:39 ccm fir\r\na=rtcp-fb:39 nack\r\na=rtcp-fb:39 nack pli\r\na=fmtp:39 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f\r\na=rtpmap:40 rtx/90000\r\na=fmtp:40 apt=39\r\na=rtpmap:45 AV1/90000\r\na=rtcp-fb:45 goog-remb\r\na=rtcp-fb:45 transport-cc\r\na=rtcp-fb:45 ccm fir\r\na=rtcp-fb:45 nack\r\na=rtcp-fb:45 nack pli\r\na=fmtp:45 level-idx=5;profile=0;tier=0\r\na=rtpmap:46 rtx/90000\r\na=fmtp:46 apt=45\r\na=rtpmap:98 VP9/90000\r\na=rtcp-fb:98 goog-remb\r\na=rtcp-fb:98 transport-cc\r\na=rtcp-fb:98 ccm fir\r\na=rtcp-fb:98 nack\r\na=rtcp-fb:98 nack pli\r\na=fmtp:98 profile-id=0\r\na=rtpmap:99 rtx/90000\r\na=fmtp:99 apt=98\r\na=rtpmap:100 VP9/90000\r\na=rtcp-fb:100 goog-remb\r\na=rtcp-fb:100 transport-cc\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 nack pli\r\na=fmtp:100 profile-id=2\r\na=rtpmap:101 rtx/90000\r\na=fmtp:101 apt=100\r\na=rtpmap:123 red/90000\r\na=rtpmap:124 rtx/90000\r\na=fmtp:124 apt=123\r\na=rtpmap:125 ulpfec/90000\r\na=ssrc-group:FID 2049894878 234304351\r\na=ssrc:2049894878 cname:XTjS0iKTUJWj00ys\r\na=ssrc:234304351 cname:XTjS0iKTUJWj00ys\r\n",
              "type": "answer"
            }
         */

        sock.emit("sendAnswer", { roomId: ROOM_ID, answer })


      }
    })

    // 呼叫端接收到 接收端的answer
    sock.on("receiveAnswer", (answer) => {
      if (caller.value) {
        // 设置远端的answer的信息
        peer.value!.setRemoteDescription(answer)
      }
    })

    sock.on("receiveCandidate", async (candidate, from) => {
      if (peer.value && candidate) {
        if (caller.value && from === "called") {
          await peer.value.addIceCandidate(candidate).catch((error) => {
            console.log("err", error)
          })
        }
        if (called.value && from === "caller") {
          await peer.value.addIceCandidate(candidate).catch((error) => {
            console.log("err", error)
          })
        }
      }
    })

    sock.on("hangUp", () => {
      reset()
    })
  })

  socket.value = sock
})
</script>

<template>
  <div class="flex items-center flex-col text-center p-12 h-screen">
    <div class="relative h-full mb-4">
      <video ref="localVideo" class="w-96 h-full bg-gray-200 mb-4 object-cover"></video>
      <video ref="remoteVideo" class="w-32 h-48 absolute bottom-0 right-0 object-cover"></video>
      <div v-if="caller && calling" class="absolute top-2/3 left-36 flex flex-col items-center">
        <p class="mb-4 text-white">等待对方接听...</p>
        <img @click="hangUp" src="/refuse.svg" class="w-16 cursor-pointer" alt="">
      </div>
      <div v-if="called && calling" class="absolute top-2/3 left-32 flex flex-col items-center">
        <p class="mb-4 text-white">收到视频邀请...</p>
        <div class="flex">
          <img @click="hangUp" src="/refuse.svg" class="w-16 cursor-pointer mr-4" alt="">
          <img @click="acceptCall" src="/accept.svg" class="w-16 cursor-pointer" alt="">
        </div>
      </div>
    </div>
    <div class="flex gap-2 mb-4">
      <button class="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white cursor-pointer"
        @click="callRemote">发起视频</button>
      <button class="rounded-md bg-red-600 px-4 py-2 text-sm font-semibold text-white cursor-pointer"
        @click="hangUp">挂断视频</button>
    </div>
  </div>
</template>